﻿using System;
using System.Web;
using System.Web.SessionState;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Xml;
using System.IO;

using Gift.Model;
using Gift.WebApp;

namespace WebApp.cn.ashx
{
    public class orderPayHandler : IHttpHandler, IRequiresSessionState
    {

        readonly BasePage thePage = new BasePage();

        /// <summary>
        /// 您将需要在您网站的 web.config 文件中配置此处理程序，
        /// 并向 IIS 注册此处理程序，然后才能进行使用。有关详细信息，
        /// 请参见下面的链接: http://go.microsoft.com/?linkid=8101007
        /// </summary>
        #region IHttpHandler Members


        protected string remindSetXmlPath = "/xml/remind_set.xml";
        tbUser oUser = new tbUser();


        public bool IsReusable
        {
            // 如果无法为其他请求重用托管处理程序，则返回 false。
            // 如果按请求保留某些状态信息，则通常这将为 false。
            get { return true; }
        }

        public void ProcessRequest(HttpContext context)
        {

            if (context.Request.Form["orderNo"] != null)
            {
                DataTable orderByOrderNo = BaseFactory.theOrder.GetOrderByOrderNo(context.Request.Form["orderNo"]);
                if (orderByOrderNo.Rows.Count > 0)
                {
                    DataRow row = orderByOrderNo.Rows[0];
                    DataRow row2 = BaseFactory.theUser.GetUserById(thePage.LoginUserMember.ClientUser.id).Rows[0];
                    if ((row["payment"].ToString() == "预存款") || (context.Request.Form["payment"] != null))
                    {
                        if (Convert.ToDecimal(row2["money"]) >= Convert.ToDecimal(row["orderTotal"]))
                        {
                            this.oUser.id = Convert.ToInt32(row2["id"]);
                            this.oUser.money = Convert.ToDecimal(row2["money"]) - Convert.ToDecimal(row["orderTotal"]);
                            this.oUser.payPoints = Convert.ToInt32(row2["payPoints"]) + Convert.ToInt32(row["presentedIntegra"]);
                            if (BaseFactory.theUser.ModifyUserMoneyAndPayPoints(this.oUser))
                            {
                                if (BaseFactory.theOrder.ModifyPayStatusByOrderNo(context.Request.Form["orderNo"], 1))
                                {
                                    BaseFactory.theOrder.ModifyPaymentByOrderNo(context.Request.Form["orderNo"], "预存款", "预存款");
                                    XmlDocument document = new XmlDocument();
                                    document.Load(HttpContext.Current.Server.MapPath(this.remindSetXmlPath));
                                    XmlElement element = document.SelectSingleNode("set") as XmlElement;
                                    XmlElement element2 = document.SelectSingleNode("set").ChildNodes[1] as XmlElement;
                                    string str = File.ReadAllText(HttpContext.Current.Server.MapPath("/cn/txt_template/order_payment.txt"));
                                    if (element2.GetAttribute("mail_remind") == "true")
                                    {
                                        SendMailMessage message = new SendMailMessage();
                                        message.subject = "订单支付成功";
                                        message.body = str.Replace("[userName]", thePage.LoginUserMember.ClientUser.userName).Replace("[orderNo]", row["orderNo"].ToString()).Replace("[orderTotal]", string.Format("{0:C}", Convert.ToDecimal(row["orderTotal"])));
                                        message.html = true;
                                        DataTable allEnabledMail = BaseFactory.theMail.GetAllEnabledMail();
                                        Random random = new Random();
                                        DataRow row3 = allEnabledMail.Rows[random.Next(allEnabledMail.Rows.Count - 1)];
                                        message.from = row3["fromAddress"].ToString();
                                        message.fromName = row3["fromName"].ToString();
                                        message.mailDomain = row3["mailDomain"].ToString();
                                        message.mailDomainPort = Convert.ToInt32(row3["mailDomainPort"]);
                                        message.mailServerUserName = row3["mailServerUserName"].ToString();
                                        message.mailServerPassWord = row3["mailServerPassWord"].ToString();
                                        if (element2.GetAttribute("notice_member") == "true")
                                        {
                                            message.mailTo = thePage.LoginUserMember.ClientUser.email;
                                            message.RuleSend();
                                        }
                                        if (element2.GetAttribute("notice_admin") == "true")
                                        {
                                            message.mailTo = element.GetAttribute("remind_email");
                                            message.RuleSend();
                                        }
                                    }
                                }
                                context.Response.Write("1");
                            }
                            else
                            {
                                context.Response.Write("0");
                            }
                        }
                        else
                        {
                            context.Response.Write("0");
                        }
                    }
                }
            }
        }

        #endregion
    }
}
